<?php

namespace App\Http\Controllers\Seller;

use App\Library\Mall\ItemTrait;
use App\Models\ItemCatlog;
use App\Models\ItemCatlogProps;
use App\Models\ItemProps;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\URL;

class ItemController extends BaseController
{
    use ItemTrait;

    /**
     * ItemController constructor.
     * @param Request $request
     */
    public function __construct(Request $request)
    {
        parent::__construct($request);
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Exception
     */
    public function index(){

        $query = $this->user()->items();
        $status = $this->request->input('status');
        if ($status === 'offSale') {
            $query = $query->offSale();
            $this->assign(['menu'=>'off_sale_item']);
        }else {
            $query = $query->onSale();
            $this->assign(['menu'=>'on_sale_item']);
        }

        $items = $query->orderByDesc('itemid')->paginate(10);
        $this->assign([
            'items'=>$items,
            'pagination'=>$items->appends(['status'=>$status])->render(),
            'status'=>$status,
        ]);

        return $this->view('seller.item.list');
    }

    /**
     * 出售宝贝
     */
    public function sell(){

        $itemid = $this->request->input('itemid');
        if ($this->isOnSubmit()){
            $catid = $this->request->input('catid');
            return redirect('/seller/item/publish?catid='.$catid.'&itemid='.intval($itemid));
        }else {

            $catlogList = [];
            ItemCatlog::all(['catid', 'fid', 'name'])->map(function ($catlog) use (&$catlogList) {
                $catlogList[$catlog->fid][] = $catlog;
            });

            $this->assign([
                'catlogList'=>$catlogList,
                'menu'=>'sell'
            ]);

            return $this->view('seller.item.sell');
        }
    }

    /**
     * 发布宝贝
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Exception
     */
    public function publish(){

        $catid  = intval($this->request->input('catid'));
        $itemid = intval($this->request->input('itemid'));
        $this->assign([
            'menu'=>'sell',
            'itemid'=>$itemid,
            'catid'=>$catid,
            'item'=>[
                'title'=>'',
                'subtitle'=>'',
                'price'=>'1.00',
                'market_price'=>'1.00',
                'stock'=>100,
                'shipping_fee'=>'0.00',
                'on_sale'=>1
            ],
            'content'=>[
                'content'=>''
            ],
            'catlog'=>ItemCatlog::find($catid)
        ]);

        $images = [
            [
                'id'=>0,
                'thumb'=>'',
                'image'=>''
            ],
            [
                'id'=>0,
                'thumb'=>'',
                'image'=>''
            ],
            [
                'id'=>0,
                'thumb'=>'',
                'image'=>''
            ],
            [
                'id'=>0,
                'thumb'=>'',
                'image'=>''
            ],
            [
                'id'=>0,
                'thumb'=>'',
                'image'=>''
            ],
        ];

        if ($itemid) {
            $item = $this->user()->items()->find($itemid);
            if ($item)
            {
                $this->assign([
                    'item'=> $item,
                    'content'=> $item->content
                ]);

                $item->images()->orderBy('displayorder')->orderBy('id')
                    ->get()->map(function ($image, $index) use (&$images){
                        $images[$index] = $image;
                    });
            }
        }

        $this->assign(['images'=>$images]);
        return $this->view('seller.item.publish');
    }

    protected function sendStoredItemResponse(Request $request, $item)
    {
        $item->poster = $item->images->last()->image;
        $item->save();

        if ($request->input('itemid')) {
            return $this->messager()->message(trans('sysmessage.info update success'))
                ->links([
                    [trans('common.reedit'), URL::full()],
                    [trans('mall.sell_item'), url('/seller/item/sell')],
                    [trans('sysmessage.back_list'), url('/seller/item')]
                ])->render();
        }else {
            return $this->messager()->message(trans('sysmessage.info save success'))
                ->links([
                    [trans('mall.sell_item'), url('/seller/item/sell')],
                    [trans('common.back_list'), url('/seller/item')]
                ])->render();
        }
    }

    protected function sendStoredItemFailedResponse(Request $request)
    {
        return $this->messager()->error()->message(trans('sysmessage.invalid parameter'))->render();
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function getProps()
    {
        $catid = $this->request->input('catid');
        $properties = ItemCatlogProps::where('catid', $catid)->orderBy('prop_id')->get();

        $itemid = $this->request->input('itemid');
        $itemProps = [];
        ItemProps::where('itemid', $itemid)->get()->map(function ($prop) use (&$itemProps) {
            $itemProps[$prop->prop_id] = $prop;
        });

        $table = '<table class="props-table" cellpadding="0" cellspacing="0"><tr>';
        foreach ($properties as $key=>$prop) {
            $default = $prop->default;
            if (isset($itemProps[$prop->prop_id])){
                $default = ($itemProps[$prop->prop_id])->prop_value;
            }
            $name = 'properties['.$prop->prop_id.']';
            if ($prop->type == 'text') {
                $table.= '<td class="td-label">'.$prop->title.'</td>';
                $table.= '<td class="td-input"><input type="text" class="form-control w200" name="'.$name.'" value="'.$default.'"></td>';
            }

            if ($prop->type == 'textarea') {
                $table.= '<td class="td-label">'.$prop->title.'</td>';
                $table.= '<td class="td-input"><textarea class="form-control" name="'.$name.'" style="width: 200px; height: 60px">'.$default.'</textarea></td>';
            }

            if ($prop->type == 'number') {
                $table.= '<td class="td-label">'.$prop->title.'</td>';
                $table.= '<td class="td-input"><input type="number" class="form-control w200" name="'.$name.'" value="'.$default.'"></td>';
            }

            if ($prop->type == 'calendar') {
                $table.= '<td class="td-label">'.$prop->title.'</td>';
                $table.= '<td class="td-input"><input type="text" class="form-control w200" readonly="readonly" onclick="WdatePicker()" name="'.$name.'" value="'.$default.'"></td>';
            }

            if ($prop->type == 'select') {
                $table.= '<td class="td-label">'.$prop->title.'</td>';
                $table.= '<td class="td-input"><select class="form-control w200" name="'.$name.'">';

                $options = explode("\n", $prop->options);
                foreach ($options as $k=>$v) {
                    $selected = $v == $default ? ' selected="selected"' : '';
                    $table.= '<option value="'.$v.'"'.$selected.'>'.$v.'</option>';
                }
                $table.= '</select></td>';
            }

            if ($prop->type == 'radio') {
                $table.= '<td class="td-label">'.$prop->title.'</td>';
                $table.= '<td class="td-input">';

                $options = explode("\n", $prop->options);
                foreach ($options as $k=>$v) {
                    $checked = $v == $default ? ' checked="checked"' : '';
                    $table.= '<label><input type="radio" name="'.$name.'" value="'.$v.'"'.$checked.'>'.$v.'</label>';
                }
                $table.= '</td>';
            }

            if ($prop->type == 'checkbox') {
                $table.= '<td class="td-label">'.$prop->title.'</td>';
                $table.= '<td class="td-input">';

                $options = explode("\n", $prop->options);
                foreach ($options as $k=>$v) {
                    $checked = $v == $default ? ' checked="checked"' : '';
                    $table.= '<label><input type="checkbox" name="'.$name.'[]" value="'.$v.'"'.$checked.'>'.$v.'</label>';
                }
                $table.= '</td>';
            }

            if (($key + 1)%2 == 0) {
                $table.= '</tr><tr>';
            }
        }
        $table.= '</tr></table>';
        return ajaxReturn(['table'=>$table]);
    }
}
